package com.tuu.controller;
import com.tuu.configBean.RedisUtil;
import com.tuu.mapper.UserMapper;
import com.tuu.pojo.JwtUser;
import com.tuu.service.UserService;
import com.tuu.utils.*;
import com.tuu.vo.ResultBody;
import com.tuu.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private  JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Value("${jwt.pVersionName}")
    String pVersionName;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @PostMapping("/login2")
    public Object login2(@RequestBody JwtUser loginInfo, HttpServletRequest request) throws Exception {
        System.out.println("进入login2");
        //设置ObjectThreadLocal从request得到ip  加入到token claims中
        //ObjectThreadLocal.set(request);
        BrowerUtils bu = BrowerUtils.getBrowerInfo(request);
        //生成token后，清除下面的GlobalMap
        Map<String, String> deviceInfo = new HashMap<>();
        //deviceInfo.put("browser_name", bu.getBrowserName());
        //deviceInfo.put("system_name", bu.getOperatingSystem());
        //deviceInfo.put("browser_version", bu.getBrowserVersion());
        //GlobalMap.set("browser_name", bu.getBrowserName());
        //GlobalMap.set("system_name", bu.getOperatingSystem());
        //GlobalMap.set("browser_version", bu.getBrowserVersion());
        System.out.println("浏览器" + bu.getBrowserName());
        System.out.println("系统" + bu.getOperatingSystem());
        System.out.println("浏览器版本" + bu.getBrowserVersion());
        String token = null;
        Map<String, Object> map = null;
        map = userService.login2(deviceInfo,loginInfo);
        //System.out.println(token);
        deviceInfo=null;
        if (map.get("token") != null) {
            System.out.println("token已经产生"+map.get("token"));
            return ResultBody.success(map);
        }
        return ResultBody.error("用户名密码错误，请重试");
    }
    /*
    由于spring的RequestParam注解接收的参数是来自于requestHeader中，
    即请求头，也就是在url中，格式为xxx?username=123&password=456，
    而RequestBody注解接收的参数则是来自于requestBody中，即请求体中。
     */
    @GetMapping("/setToken")
    public Object setToken(@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(token);
        Cookie cookie = new Cookie("cookiename", token);
        response.addCookie(cookie);
        return new ResultVO();
    }
    //
    @GetMapping("/checkTokenCookie")
    public Object checkToken(@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("检查token。。。");
        System.out.println(token);
        Map<String, Object> map = new HashMap<>();
        map.put("cookies", JWTUtils.checkJWT(token, request));
        //map.put("user_name",GlobalMap.get("user_name"));
        //GlobalMap.clear();
        return ResultBody.success(map);
    }
    @GetMapping("/checkTokenCookie2")
    public Object checkToken2(@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("检查token。。。");
        System.out.println(token);
        Map<String, Object> map = new HashMap<>();
        map.put("cookies", jwtTokenUtil.validateTokenAndCookie(token, request));
        //map.put("user_name",GlobalMap.get("user_name"));
        //GlobalMap.clear();
        return ResultBody.success(map);
    }
    //第一次验证是否过期 并返回用户信息cookie
    @GetMapping("/checkToken")
    public Object checkTokenCookie(@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("检查token。。。");
        System.out.println(token);
        Map<String, Object> map = JWTUtils.checkJWT(token, request);
        //map.put("user_name",GlobalMap.get("user_name"));
        //GlobalMap.clear();
        return ResultBody.success(map);
    }
    @GetMapping("/pureCheckToken")
    public Object pureCheckToken() {
        System.out.println("进入pureCheckToken");
        return ResultBody.success("pureCheckToken_token有效");
    }
    @GetMapping("/redisTest")
    public Object redisTest(@RequestParam("token") String token) {
        redisUtil.set("bbbb", "tokentoken", 60);
        return ResultBody.error("时间不正确，请重新登陆");
    }
    @GetMapping("/decryptCode")
    public Object decryptCode(@RequestParam("enpass") String enpass) {
        System.out.println("收到" + enpass);
        if (StringUtils.isNotBlank(enpass)) {
            String originStr = RSAUtils.decryptBase64(enpass);
            System.out.println("解密为:" + originStr);
        }
        return "ooo";
    }
    @PostMapping("/postDecryptCode")
    public Object postDecryptCode(@RequestParam("enpass") String enpass) {
        System.out.println("post收到" + enpass);
        if (StringUtils.isNotBlank(enpass)) {
            String originStr = MyRSAUtils.decryptBase64(enpass);
            System.out.println("解密为:" + originStr);
        }
        return ResultBody.success("解密成功");
    }
    @GetMapping("/getPasswprdKey")
    public ResultBody getPasswprdKey(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        try {
            String publickey = MyRSAUtils.generateBase64PublicKey();
            System.out.println("公钥为："+publickey);
            return ResultBody.success(publickey);
        } catch (Exception e) {
            // TODO: handle exception
            return ResultBody.error("获取公钥错误");
        }
    }
    @GetMapping("/logout2")
    public ResultBody logout(@RequestParam("token") String token, HttpServletRequest request) throws Exception {
        //logout是security的  不能使用
        System.out.println("进入logout。。。。");
        userService.logout(token, request);
        return ResultBody.success("退出成功。。。");
    }
    @GetMapping("/createPass")
    public void pass(){
        System.out.println(passwordEncoder.encode("8888"));
    }
    //@PreAuthorize("hasAnyRole('AAA')")
    @GetMapping(value = "/aaab")
    public ResultBody testNeed() {
        return ResultBody.success("hasAnyRole。。。AAA");
    }
    //@PreAuthorize("hasAnyRole('BBB')")
    @GetMapping(value = "/bbba")
    public ResultBody bbb() {
        return ResultBody.success("hasAnyRole。。。BBB");
    }
    @GetMapping(value = "/sendRedis")
    public ResultBody sendRedis() {
        //publish user_role bbb 在redis客户端给主题发消息
        redisTemplate.convertAndSend("user_role",String.valueOf(Math.random()));
        redisTemplate.convertAndSend("role_permission",String.valueOf(Math.random()));
        return ResultBody.success("sendRedis成功");
    }
    @GetMapping(value = "/annymbb")
    public void annym() {
        Random r=new Random();
        redisUtil.set(pVersionName,String.valueOf(Math.random()));
        System.out.println("pV版本号是"+redisUtil.get(pVersionName));
    }
}